﻿using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using ConfigurationSettings;
using FileSystemControls.Support;

namespace FileSystemControls.ListViewItems
{
    /// <summary>
    /// A collection of shares
    /// </summary>
    public class ShareCollection : IList<ShareListViewItem> //, IEnumerable<Share>
    {
        #region Private Member Variables

        /// <summary>The name of the server this collection represents</summary>
        private string _server;

        /// <summary>Boolean indicating that access is denied to this resource.</summary>
        private bool _accessDenied = false;

        //private List<Share> _innerList;
        private List<ShareListViewItem> _innerList;

        #endregion

        #region Constructor

        /// <summary>
        /// Default constructor - local machine
        /// </summary>
        //public ShareCollection() 
        //{
        //    _server = string.Empty;
        //    EnumerateShares(_server, this, ref _accessDenied);
        //}

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="Server"></param>
        public ShareCollection(string server)
        {
            //_innerList = new List<Share>();  ShareListViewItem
            _innerList = new List<ShareListViewItem>();

            _server = server;
            EnumerateShares(_server, this, ref _accessDenied);
        }

        #endregion

        #region Platform

        /// <summary>
        /// Is this an NT platform?
        /// </summary>
        protected static bool IsNT
        {
            get { return (PlatformID.Win32NT == Environment.OSVersion.Platform); }
        }

        /// <summary>
        /// Returns true if this is Windows 2000 or higher
        /// </summary>
        protected static bool IsW2KUp
        {
            get
            {
                OperatingSystem os = Environment.OSVersion;
                if (PlatformID.Win32NT == os.Platform && os.Version.Major >= 5)
                    return true;
                else
                    return false;
            }
        }

        #endregion

        #region Interop

        #region Constants

        ///// <summary>Maximum path length</summary>
        //protected const int MAX_PATH = 260;
        /// <summary>No error</summary>
        protected const int NO_ERROR = 0;
        /// <summary>Access denied</summary>
        protected const int ERROR_ACCESS_DENIED = 5;
        /// <summary>Access denied</summary>
        protected const int ERROR_WRONG_LEVEL = 124;
        /// <summary>More data available</summary>
        protected const int ERROR_MORE_DATA = 234;
        ///// <summary>Not connected</summary>
        //protected const int ERROR_NOT_CONNECTED = 2250;
        ///// <summary>Level 1</summary>
        //protected const int UNIVERSAL_NAME_INFO_LEVEL = 1;
        /// <summary>Max extries (9x)</summary>
        protected const int MAX_SI50_ENTRIES = 20;

        #endregion

        #region Structures

        /// <summary>Unc name</summary>
        //[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
        //protected struct UNIVERSAL_NAME_INFO 
        //{
        //    [MarshalAs(UnmanagedType.LPTStr)]
        //    public string lpUniversalName;
        //}

        /// <summary>Share information, NT, level 2</summary>
        /// <remarks>
        /// Requires admin rights to work. 
        /// </remarks>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        protected struct SHARE_INFO_2
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            public string NetName;
            public ShareType ShareType;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string Remark;
            public int Permissions;
            public int MaxUsers;
            public int CurrentUsers;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string Path;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string Password;
        }

        /// <summary>Share information, NT, level 1</summary>
        /// <remarks>
        /// Fallback when no admin rights.
        /// </remarks>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        protected struct SHARE_INFO_1
        {
            [MarshalAs(UnmanagedType.LPWStr)]
            public string NetName;
            public ShareType ShareType;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string Remark;
        }

        /// <summary>Share information, Win9x</summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        protected struct SHARE_INFO_50
        {
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 13)]
            public string NetName;

            public byte bShareType;
            public ushort Flags;

            [MarshalAs(UnmanagedType.LPTStr)]
            public string Remark;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string Path;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 9)]
            public string PasswordRW;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 9)]
            public string PasswordRO;

            public ShareType ShareType
            {
                get { return (ShareType)((int)bShareType & 0x7F); }
            }
        }

        /// <summary>Share information level 1, Win9x</summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        protected struct SHARE_INFO_1_9x
        {
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 13)]
            public string NetName;
            public byte Padding;

            public ushort bShareType;

            [MarshalAs(UnmanagedType.LPTStr)]
            public string Remark;

            public ShareType ShareType
            {
                get { return (ShareType)((int)bShareType & 0x7FFF); }
            }
        }

        //[StructLayout(LayoutKind.Sequential)]
        //private struct structNetResource
        //{
        //    public int iScope;
        //    public int iType;
        //    public int iDisplayType;
        //    public int iUsage;
        //    public string sLocalName;
        //    public string sRemoteName;
        //    public string sComment;
        //    public string sProvider;
        //}

        //private const int RESOURCETYPE_DISK = 0x1;

        #endregion

        #region DLL imports

        // /// <summary>Connect To Share with username and password</summary>
        //[DllImport("mpr", CharSet=CharSet.Auto)]
        //private static extern int WNetAddConnection2A(ref structNetResource pstNetRes, 
        //    string psPassword, string psUsername, int piFlags);

        // /// <summary>Get a UNC name</summary>
        //[DllImport("mpr", CharSet=CharSet.Auto)]
        //protected static extern int WNetGetUniversalName (string lpLocalPath,
        //    int dwInfoLevel, ref UNIVERSAL_NAME_INFO lpBuffer, ref int lpBufferSize);

        // /// <summary>Get a UNC name</summary>
        //[DllImport("mpr", CharSet=CharSet.Auto)]
        //protected static extern int WNetGetUniversalName (string lpLocalPath,
        //    int dwInfoLevel, IntPtr lpBuffer, ref int lpBufferSize);

        #endregion

        #region Enumerate shares

        /// <summary>
        /// Enumerates the shares on Windows NT
        /// </summary>
        /// <param name="server">The server name</param>
        /// <param name="shares">The ShareCollection</param>
        protected static void EnumerateSharesNT(string server, ShareCollection shares, ref bool accessDenied)
        {
            int level = 2;
            int hResume = 0;
            IntPtr pBuffer = IntPtr.Zero;

            try
            {
                int entriesRead;
                int totalEntries;
                int nRet = NativeMethods.NetShareEnum(server, level, out pBuffer, -1,
                                                      out entriesRead, out totalEntries, ref hResume);

                if (ERROR_ACCESS_DENIED == nRet)
                {
                    //Need admin for level 2, drop to level 1
                    level = 1;
                    nRet = NativeMethods.NetShareEnum(server, level, out pBuffer, -1,
                        out entriesRead, out totalEntries, ref hResume);
                    accessDenied = true;
                }

                if (NO_ERROR == nRet && entriesRead > 0)
                {
                    Type t = level == 2 ? typeof (SHARE_INFO_2) : typeof (SHARE_INFO_1);

                    int offset = Marshal.SizeOf(t);

                    IntPtr currentPtr = pBuffer;

                    for (int i = 0; i < totalEntries; i++)
                    {

                        if (1 == level)
                        {
                            SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, t);
                            shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
                        }
                        else
                        {
                            SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(currentPtr, t);
                            shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
                        }

                        currentPtr = new IntPtr(currentPtr.ToInt64() + offset);

                    }
                }
            }
            finally
            {
                // Clean up buffer allocated by system
                if (IntPtr.Zero != pBuffer)
                    NativeMethods.NetApiBufferFree(pBuffer);
            }
        }

        /// <summary>
        /// Enumerates the shares on Windows 9x
        /// </summary>
        /// <param name="server">The server name</param>
        /// <param name="shares">The ShareCollection</param>
        protected static void EnumerateShares9x(string server, ShareCollection shares, ref bool accessDenied)
        {
            int level = 50;
            int nRet = 0;
            ushort entriesRead, totalEntries;

            accessDenied = false;
            Type t = typeof(SHARE_INFO_50);
            int size = Marshal.SizeOf(t);
            ushort cbBuffer = (ushort)(MAX_SI50_ENTRIES * size);
            //On Win9x, must allocate buffer before calling API
            IntPtr pBuffer = Marshal.AllocHGlobal(cbBuffer);

            try
            {
                nRet = NativeMethods.NetShareEnum(server, level, pBuffer, cbBuffer,
                    out entriesRead, out totalEntries);

                if (ERROR_WRONG_LEVEL == nRet)
                {
                    level = 1;
                    t = typeof(SHARE_INFO_1_9x);
                    size = Marshal.SizeOf(t);

                    nRet = NativeMethods.NetShareEnum(server, level, pBuffer, cbBuffer,
                        out entriesRead, out totalEntries);
                }

                if (NO_ERROR == nRet || ERROR_MORE_DATA == nRet)
                {
                    for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += size)
                    {
                        IntPtr pItem = new IntPtr(lpItem);

                        if (1 == level)
                        {
                            SHARE_INFO_1_9x si = (SHARE_INFO_1_9x)Marshal.PtrToStructure(pItem, t);
                            shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
                        }
                        else
                        {
                            SHARE_INFO_50 si = (SHARE_INFO_50)Marshal.PtrToStructure(pItem, t);
                            shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
                        }
                    }
                }
                else
                    Console.WriteLine(nRet);

            }
            finally
            {
                //Clean up buffer
                Marshal.FreeHGlobal(pBuffer);
            }
        }

        /// <summary>
        /// Enumerates the shares
        /// </summary>
        /// <param name="server">The server name</param>
        /// <param name="shares">The ShareCollection</param>
        protected static void EnumerateShares(string server, ShareCollection shares, ref bool accessDenied)
        {
            if (null != server && 0 != server.Length && !IsW2KUp)
            {
                server = server.ToUpper();

                // On NT4, 9x and Me, server has to start with "\\"
                if (!('\\' == server[0] && '\\' == server[1]))
                    server = @"\\" + server;
            }
            accessDenied = false;

            if (IsNT)
                EnumerateSharesNT(server, shares, ref  accessDenied);
            else
                EnumerateShares9x(server, shares, ref  accessDenied);
        }

        #endregion

        #endregion

        #region Static methods (commented out)

        /// <summary>
        /// Returns true if fileName is a valid local file-name of the form:
        /// X:\, where X is a drive letter from A-Z
        /// </summary>
        /// <param name="fileName">The filename to check</param>
        /// <returns></returns>
        //public static bool IsValidFilePath(string fileName) 
        //{
        //    if (null == fileName || 0 == fileName.Length) return false;

        //    char drive = char.ToUpper(fileName[0]);
        //    if ('A' > drive || drive > 'Z') 
        //        return false;

        //    else if (Path.VolumeSeparatorChar != fileName[1]) 
        //        return false;
        //    else if (Path.DirectorySeparatorChar != fileName[2]) 
        //        return false;
        //    else 
        //        return true;
        //}

        /// <summary>
        /// Connects to remote share with username and password
        /// </summary>
        /// <param name="UNCcomputer">Remote Computer</param>
        /// <param name="username">User Name</param>
        /// <param name="password">Password</param>
        /// <returns>nothing, just hooks up to remote share</returns>
        //public static void ConnectToComputer(string UNCcomputer, string username, string password) 
        //{  
        //    structNetResource stNetRes = new structNetResource();
        //    stNetRes.iScope = 2;
        //    stNetRes.iType = RESOURCETYPE_DISK;
        //    stNetRes.iDisplayType = 3;
        //    stNetRes.iUsage = 1;
        //    stNetRes.sRemoteName = UNCcomputer;
        //    stNetRes.sLocalName = "IRC$";
        //    int iFlags = 0;
        //    if (username == "") {username = null;}
        //    if (password == "") {password = null;}
        //    int result = WNetAddConnection2A(ref stNetRes, password, username, iFlags);
        //}

        /// <summary>
        /// Returns the UNC path for a mapped drive or local share.
        /// </summary>
        /// <param name="fileName">The path to map</param>
        /// <returns>The UNC path (if available)</returns>
        //public static string PathToUnc(string fileName) 
        //{
        //    if (null == fileName || 0 == fileName.Length) return string.Empty;

        //    fileName = Path.GetFullPath(fileName);
        //    if (!IsValidFilePath(fileName)) return fileName;

        //    int nRet = 0;
        //    UNIVERSAL_NAME_INFO rni = new UNIVERSAL_NAME_INFO();
        //    int bufferSize = Marshal.SizeOf(rni);

        //    nRet = WNetGetUniversalName(
        //        fileName, UNIVERSAL_NAME_INFO_LEVEL, 
        //        ref rni, ref bufferSize);

        //    if (ERROR_MORE_DATA == nRet) 
        //    {
        //        IntPtr pBuffer = Marshal.AllocHGlobal(bufferSize);;
        //        try 
        //        {
        //            nRet = WNetGetUniversalName(
        //                fileName, UNIVERSAL_NAME_INFO_LEVEL, 
        //                pBuffer, ref bufferSize);

        //            if (NO_ERROR == nRet) 
        //            {
        //                rni = (UNIVERSAL_NAME_INFO)Marshal.PtrToStructure(pBuffer,
        //                    typeof(UNIVERSAL_NAME_INFO));
        //            }
        //        }
        //        finally 
        //        {
        //            Marshal.FreeHGlobal(pBuffer);
        //        }
        //    }

        //    switch (nRet) 
        //    {
        //        case NO_ERROR:
        //            return rni.lpUniversalName;

        //        case ERROR_NOT_CONNECTED:
        //            //Local file-name
        //            ShareCollection shi = LocalShares;
        //            if (null != shi)
        //            {
        //                Share share = shi[fileName];
        //                if (null != share)
        //                {
        //                    string path = share.Path;
        //                    if (null != path && 0 != path.Length)
        //                    {
        //                        int index = path.Length;
        //                        if (Path.DirectorySeparatorChar != path[path.Length - 1])
        //                            index++;

        //                        if (index < fileName.Length)
        //                            fileName = fileName.Substring(index);
        //                        else
        //                            fileName = string.Empty;

        //                        fileName = Path.Combine(share.ToString(), fileName);
        //                    }
        //                }
        //            }

        //            return fileName;

        //        default:
        //            Console.WriteLine("Unknown return value: {0}", nRet);
        //            return string.Empty;
        //    }
        //}

        /// <summary>
        /// Returns the local <see cref="Share"/> object with the best match
        /// to the specified path.
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        //public static Share PathToShare(string fileName) 
        //{
        //    if (null == fileName || 0 == fileName.Length) return null;

        //    fileName = Path.GetFullPath(fileName);
        //    if (!IsValidFilePath(fileName)) return null;

        //    ShareCollection shi = LocalShares;
        //    if (null == shi) 
        //        return null;
        //    else 
        //        return shi[fileName];
        //}

        #endregion

        #region Local shares

        /// <summary>The local shares</summary>
        //private static ShareCollection _local = null;

        /// <summary>
        /// Return the local shares
        /// </summary>
        //public static ShareCollection LocalShares 
        //{
        //    get 
        //    {
        //        if (null == _local) 
        //            _local = new ShareCollection();

        //        return _local;
        //    }
        //}

        /// <summary>
        /// Return the shares for a specified machine
        /// </summary>
        /// <param name="server">Server name in UNC format.</param>
        /// <returns></returns>
        public static ShareCollection GetShares(string server)
        {
            return new ShareCollection(server);
        }

        #endregion

        #region Add

        //protected void Add(Share share)
        //{
        //    InnerList.Add(share);
        //}

        //public void Add(Share item)
        //{
        //    base.Add(item);
        //}

        #endregion

        #region Properties (commented out)

        /// <summary>
        /// Returns true if Access Denied error
        /// </summary>
        //public bool AccessDenied 
        //{
        //    get { return _accessDenied; }
        //}

        /// <summary>
        /// Returns the name of the server this collection represents
        /// </summary>
        //public string Server 
        //{
        //    get { return _server; }
        //}

        /// <summary>
        /// Returns the <see cref="Share"/> at the specified index.
        /// </summary>
        //public Share this[int index] 
        //{
        //    get { return (Share)InnerList[index]; }
        //}

        /// <summary>
        /// Returns the <see cref="Share"/> which matches a given local path
        /// </summary>
        /// <param name="path">The path to match</param>
        //public Share this[string path] 
        //{
        //    get 
        //    {
        //        if (null == path || 0 == path.Length) return null;

        //        path = Path.GetFullPath(path);
        //        if (!IsValidFilePath(path)) return null;

        //        Share match = null;

        //        for(int i=0; i<InnerList.Count; i++) 
        //        {
        //            Share s = (Share)InnerList[i];

        //            if (s.IsFileSystem && s.MatchesPath(path)) 
        //            {
        //                //Store first match
        //                if (null == match) 
        //                    match = s;

        //                // If this has a longer path,
        //                // and this is a disk share or match is a special share, 
        //                // then this is a better match
        //                else if (match.Path.Length < s.Path.Length) 
        //                {
        //                    if (ShareType.Disk == s.ShareType || ShareType.Disk != match.ShareType)
        //                        match = s;
        //                }
        //            }
        //        }

        //        return match;
        //    }
        //}

        #endregion

        //public IEnumerator<Share> GetEnumerator()
        //{
        //    return new ShareEnumerator(this);
        //}

        //IEnumerator IEnumerable.GetEnumerator()
        //{
        //    return new ShareEnumerator(this);
        //}

        #region ** IList implementation **

        public int IndexOf(ShareListViewItem item)
        {
            return _innerList.IndexOf(item);
        }

        public void Insert(int index, ShareListViewItem item)
        {
            _innerList.Insert(index, item);
        }

        public void RemoveAt(int index)
        {
            _innerList.RemoveAt(index);
        }

        public ShareListViewItem this[int index]
        {
            get
            {
               return _innerList[index];
            }
            set
            {
                _innerList[index] = value;
            }
        }

        public void Add(string netName, string path, ShareType shareType, string remark)
        {
            _innerList.Add(new ShareListViewItem(_server, netName, path, shareType, remark));
        }

        public void Add(ShareListViewItem item)
        {
            _innerList.Add(item);
        }

        public void Clear()
        {
            _innerList.Clear();
        }

        public bool Contains(ShareListViewItem item)
        {
            foreach (ShareListViewItem CurrentItem in _innerList)
            {
                if (CurrentItem.FullName == item.FullName)
                {
                    return true;
                }
            }

            return false;
        }

        public void CopyTo(ShareListViewItem[] array, int arrayIndex)
        {
            _innerList.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _innerList.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(ShareListViewItem item)
        {
           return _innerList.Remove(item);
        }

        public IEnumerator<ShareListViewItem> GetEnumerator()
        {
            return _innerList.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _innerList.GetEnumerator();
        }

        #endregion

    }


    public class ShareEnumerator : IEnumerator<ShareListViewItem>
    {
        public ShareCollection _share;

        // Enumerators are positioned before the first element
        // until the first MoveNext() call.
        int position = -1;
        ShareListViewItem _current;

        void IDisposable.Dispose() { }

        public ShareEnumerator(ShareCollection list)
        {
            _share = list;
            _current = default(ShareListViewItem);
        }

        public bool MoveNext()
        {
            position++;
            return (position < _share.Count);
        }

        public void Reset()
        {
            position = -1;
        }

        object IEnumerator.Current
        {
            get
            {
                return Current;
            }
        }

        public ShareListViewItem Current
        {
            get
            {
                try
                {
                    return _current;
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }
}
